#include "ZLibLevel.h"
#include "cocos2d.h"

USING_NS_CC;

void ZLibLevel::compressLevel(const std::string& levelName)
{
	std::string path = CCFileUtils::sharedFileUtils()->getWriteablePath();

	char* tDest = ".gz";
	char* tJpg = ".jpg";
	char* tCc2d = ".cc2d";
	gzFile fpDest = gzopen((path + levelName + tDest).c_str(), "wb");
	FILE* fpJpg = fopen((path + levelName + tJpg).c_str(), "rb");
	FILE* fpCc2d = fopen((path + levelName + tCc2d).c_str(), "rb");
	if (fpJpg && fpCc2d)
	{
		size_t jpgSize = 0, cc2dSize = 0;

		fseek(fpJpg, 0L, SEEK_END);
		jpgSize = ftell(fpJpg);
		fseek(fpJpg, 0L, SEEK_SET);

		fseek(fpCc2d, 0L, SEEK_END);
		cc2dSize = ftell(fpCc2d);
		fseek(fpCc2d, 0L, SEEK_SET);

		size_t sizeDest = sizeof(size_t) + jpgSize + sizeof(size_t) + cc2dSize;
		char* buf = new char[sizeDest];
		
		char* ptr = buf;
		memcpy(ptr, &jpgSize, sizeof(size_t)); ptr += sizeof(size_t);
		fread(ptr, jpgSize, 1, fpJpg); ptr += jpgSize;

		memcpy(ptr, &cc2dSize, sizeof(size_t)); ptr += sizeof(size_t);
		fread(ptr, cc2dSize, 1, fpCc2d); ptr += cc2dSize;

		gzwrite(fpDest, buf, sizeDest);

		delete []buf;
		fclose(fpCc2d);
		fclose(fpJpg);
		gzclose(fpDest);
	}
}

void ZLibLevel::uncompressLevel(const std::string sourceFile)
{
	std::string path = CCFileUtils::sharedFileUtils()->getWriteablePath();
	char* tDest = ".gz";
	char* tJpg = ".jpg";
	char* tCc2d = ".cc2d";
	gzFile fpDest = gzopen((path + sourceFile + tDest).c_str(), "rb");
	FILE* fpJpg = fopen((path + sourceFile + tJpg).c_str(), "wb");
	FILE* fpCc2d = fopen((path + sourceFile + tCc2d).c_str(), "wb");

	size_t size = 0;
	gzread(fpDest, &size, sizeof(size_t));

	char* buf = new char[size];
	gzread(fpDest, buf, size);
	fwrite(buf, size, 1, fpJpg);
	delete []buf;

	gzread(fpDest, &size, sizeof(size_t));
	buf = new char[size];
	gzread(fpDest, buf, size);
	fwrite(buf, size, 1, fpCc2d);
	delete []buf;

	fclose(fpJpg);
	fclose(fpCc2d);
	gzclose(fpDest);
}